package com.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.Dao.OrderDao;
import com.sky.Service.OrderService;
import com.sky.entity.Orders;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDao orderDao;
    /**
     * 处理超时订单,每分钟执行一次
     */
    @Scheduled(cron="0 * * * * ? ")
    public void handleTimeOutOrder(){
        log.info("处理超时订单:{}", LocalDateTime.now());
        //查询超时订单，状态为待支付并且下单时间已经超过15分钟
        //根据订单时间和订单状态来查询超时的订单
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<> ();
        //当前时间减去15分钟
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-15);
        queryWrapper.eq(Orders::getStatus,Orders.PENDING_PAYMENT)
                .lt(Orders::getOrderTime,localDateTime);
        //查询超时订单
        List<Orders> orders = orderDao.selectList(queryWrapper);
        if(orders!=null&&!orders.isEmpty()){
            orders.stream().forEach(order->{
                //修改订单状态为已取消
                order.setStatus(Orders.CANCELLED);
                //设置取消原因
                order.setCancelReason("订单超时未支付，系统自动取消");
                //设置订单的取消时间
                order.setCancelTime(LocalDateTime.now());
                //更新订单信息
                orderService.updateById(order);
            });
        }
    }



    /**
     * 处理派送订单，每天凌晨一点自动执行，处理一直处于派送中的订单
//     */
    @Scheduled(cron="0 0 1 * * ? ")
    public void handleDeliveryOrder(){
        log.info("处理派送订单:{}",LocalDateTime.now());
        //查询派送订单，每天凌晨一点自动执行，处理在一直派送中的订单
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<> ();
        LocalDateTime localDateTime = LocalDateTime.now().plusMinutes(-60);
        queryWrapper.eq(Orders::getStatus,Orders.DELIVERY_IN_PROGRESS)
                .lt(Orders::getOrderTime,localDateTime);
        List<Orders> orders = orderDao.selectList(queryWrapper);
        if(orders!=null&&!orders.isEmpty()){
            orders.stream().forEach(order->{
                //修改订单状态
                order.setStatus(Orders.CANCELLED);
                orderDao.updateById(order);
            });
        }
    }
}
